package com.vitas.coin.ui.act;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BarUtils;
import com.snap.base.util.BaseUtil;
import com.snap.common.main.BaseAct;
import com.snap.util.edge.EdgePaddingMarginKt;
import com.vitas.coin.callback.DeleteListener;
import com.vitas.coin.data.bean.ChildrenVoiceBean;
import com.vitas.coin.data.bean.MusicType;
import com.vitas.coin.data.event.ContentEvent;
import com.vitas.coin.data.event.FavorEvent;
import com.vitas.coin.data.event.ListEvent;
import com.vitas.coin.databinding.ActivityPlaylistDetailBinding;
import com.vitas.coin.databinding.PopHandleBinding;
import com.vitas.coin.db.DBListener;
import com.vitas.coin.db.ListDao;
import com.vitas.coin.db.TypeDao;
import com.vitas.coin.ui.adapter.ListDetailAdapter;
import com.vitas.coin.ui.dialog.BaseDialogFragment;
import com.vitas.coin.ui.dialog.NewListDlg;
import com.vitas.coin.ui.dialog.TipDlg;
import com.vitas.coin.util.Audio;
import com.vitas.coin.util.DisplayUtil;
import com.vitas.coin.util.drag.DragSwipeCallback;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class ListAct extends BaseAct implements DeleteListener {

    ActivityPlaylistDetailBinding binding;
    ListDetailAdapter adapter;
    MusicType data;
    Handler h = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPlaylistDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EdgePaddingMarginKt.paddingVerticalSystemWindowInsets(binding.getRoot());
        BarUtils.transparentStatusBar(this);
        BarUtils.setStatusBarLightMode(this, true);

        binding.ivBack.setOnClickListener(v -> finish());
        data = getIntent().getParcelableExtra("data");
        binding.title.setText(data.name);
        if (data.list == null || data.list.isEmpty()) {
            binding.empty.setVisibility(View.VISIBLE);
        } else {
            binding.empty.setVisibility(View.GONE);
        }
        binding.rvList.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        adapter = new ListDetailAdapter(this, this, data.list);
        binding.rvList.setAdapter(adapter);

        ItemTouchHelper.Callback callback = new DragSwipeCallback(adapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
        touchHelper.attachToRecyclerView(binding.rvList);

        binding.menu.setOnClickListener(v -> showMenu());
        binding.tvPlayAll.setOnClickListener(v -> {
            if (data == null || data.list == null || data.list.isEmpty()) {
                return;
            }
            Intent i = new Intent(this, PlayAct.class);
            i.putExtra("index", 0);
            i.putParcelableArrayListExtra("list", data.list);
            startActivity(i);
        });

        initObserve();
    }

    private void initObserve() {
        BaseUtil.INSTANCE.observeForever(FavorEvent.class, new Function1<FavorEvent, Unit>() {
            @Override
            public Unit invoke(FavorEvent favorEvent) {
                for (ChildrenVoiceBean item : data.list) {
                    if (item.getId() == favorEvent.getId()) {
                        item.setCollect(favorEvent.getCollect());
                        break;
                    }
                }
                return null;
            }
        });
    }

    private void showMenu() {
        PopupWindow volumePop = new PopupWindow();
        PopHandleBinding pop = PopHandleBinding.inflate(getLayoutInflater());
        pop.tvRename.setOnClickListener(v -> {
            volumePop.dismiss();
            new NewListDlg().setTitle("重命名").setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk && value instanceof String) {
                        String s = (String) value;
                        if (!TextUtils.isEmpty(s)) {
                            binding.title.setText(s);
                            changeName(s);
                        }
                    }
                }
            }).show(getSupportFragmentManager(), "");
        });
        pop.tvDelete.setOnClickListener(v -> {
            volumePop.dismiss();
            new TipDlg().setMsg("确定要删除铃单么？\n删除后无法恢复").setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        deleteType();
                        finish();
                    }
                }
            }).show(getSupportFragmentManager(), "");
        });
        volumePop.setOutsideTouchable(true);
        volumePop.setTouchable(true);
        float i = DisplayUtil.dip2px(this, 100);
        volumePop.setWidth((int) i);
        volumePop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        volumePop.setContentView(pop.getRoot());
        volumePop.showAsDropDown(binding.menu);
    }

    private void changeName(String name) {
        data.name = name;
        new TypeDao().update(data, new DBListener() {
            @Override
            public void onResult(boolean bo, String msg, Object result) {
                h.post(() -> BaseUtil.INSTANCE.postEvent(new ListEvent()));
            }
        });
    }

    private void deleteType() {
        new TypeDao().delete(data, new DBListener() {
            @Override
            public void onResult(boolean bo, String msg, Object result) {
                if (bo) {
                    h.post(() -> {
                        BaseUtil.INSTANCE.postEvent(new ListEvent());
                    });
                }
            }
        });
    }

    boolean deleted = false;

    @Override
    public void onItemDelete(ChildrenVoiceBean bean) {
        deleted = true;
        new ListDao(data.id).delete(bean, null);
        if (data.list.isEmpty()) {
            binding.empty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onItemEdit(ChildrenVoiceBean bean) {
        Audio.editAudio(bean, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (deleted) {
            BaseUtil.INSTANCE.postEvent(new ContentEvent(data.id));
        }
    }
}
